package edu.guigu.serverservice.remote;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

// 利用Messenger实现跨进程通信
// 1 接收客户端发来的消息, 要做的是处理消息且将IBinder返回给"客户端"
public class MessengerService extends Service {

    private Messenger serverMessenger;

    public MessengerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", getClass().getSimpleName() + " onCreate: ");
        // 服务端要处理消息
        serverMessenger = new Messenger(new MessengerHandler());
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 服务端要将Messenger的Binder对象返回出云
        Log.d("TAG", getClass().getSimpleName() + " onBind: ");
        return serverMessenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("TAG", getClass().getSimpleName() + " onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", getClass().getSimpleName() + " onDestroy: ");
    }

    private Messenger clientMessenger;

    public class MessengerHandler extends android.os.Handler {
        // 处理客户端发送的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle1 = msg.getData();
                    if (bundle1 != null) {
                        String data = bundle1.getString("msg");
                        Log.i("TAG", getClass().getSimpleName() + " 收到 data = " + data);
                    }
                    break;
                case 2:
                    Bundle bundle2 = msg.getData();
                    if (bundle2 != null) {
                        String data = bundle2.getString("msg");
                        Log.i("TAG", getClass().getSimpleName() + " 收到 data = " + data);
                        // 向客户端发送消息(反馈)
                        try {
                            // TODO: 取得客户端Messenger
                            clientMessenger = msg.replyTo;
                            Bundle feedback = new Bundle();
                            feedback.putString("msg","你好，我是服务端给你的消息！");

                            Message message = Message.obtain();
                            message.setData(feedback);
                            message.what = 110;

                            clientMessenger.send(message);
                        } catch (RemoteException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }
}